package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Tunnel;
import com.hulman.oms.dao.TunnelDao;
import com.hulman.oms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @Author: maxwellens
 */
@Service
public class TunnelService
{
    @Autowired
    private TunnelDao tunnelDao;

    public List<Tunnel> findTunnels(Map<String, Object> map)
    {
        return tunnelDao.findTunnels(map);
    }

    public List<Tunnel> findAllTunnels()
    {
        return tunnelDao.findTunnels(new HashMap<>());
    }

    public List<Tunnel> findTunnelsByIds(int[] ids)
    {
        return tunnelDao.findTunnelsByIds(ids);
    }

    public Integer findTunnelsCount(Map<String, Object> map)
    {
        return tunnelDao.findTunnelsCount(map);
    }

    public Result findTunnelsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = tunnelDao.findTunnelsCount(map);
        List<Tunnel> data = tunnelDao.findTunnels(map);
        return new Result(data, count);
    }

    public Tunnel findTunnelById(Integer id)
    {
        return tunnelDao.findTunnelById(id);
    }

    public Tunnel findTunnelByName(String name)
    {
        return tunnelDao.findTunnelByName(name);
    }

    public void saveTunnel(Tunnel tunnel)
    {
        if (tunnel.getId() != null && tunnel.getId() != 0)
        {
            tunnelDao.updateTunnel(tunnel);
        } else
        {
            tunnelDao.insertTunnel(tunnel);
        }
    }

    public String parseTunnelIds(String tunnelNames)
    {

        if (StringUtil.isEmpty(tunnelNames))
        {
            return "";
        }
        String[] tunnels = tunnelNames.split(",");
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String tunnelName : tunnels)
        {
            Tunnel tunnel = tunnelDao.findTunnelByName(tunnelName);
            if (tunnel != null)
            {
                stringJoiner.add(tunnel.getId().toString());
            }
        }
        return stringJoiner.toString();
    }

    public void deleteTunnelById(Integer id)
    {
        tunnelDao.deleteTunnelById(id);
    }

    public void deleteTunnels(int[] ids)
    {
        tunnelDao.deleteTunnels(ids);
    }

}
